from git import Repo, GitCommandError
from pathlib import Path
from datetime import datetime
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd
import seaborn as sns
import os
import sys


def create_comparison_report(all_repos_data):
    """创建对比报告文档"""
    # 生成图表路径
    cumulative_path = generate_cumulative_comparison_plot(all_repos_data)
    total_commits_path = generate_total_commits_plot(all_repos_data)

    # 使用相对路径
    cumulative_relative = Path(cumulative_path).relative_to(Path.cwd())
    total_commits_relative = Path(total_commits_path).relative_to(Path.cwd())

    # 构建报告内容
    report = "# AIFlowY vs RuoYi-Vue \n\n"
    report += "## Cumulative submission growth comparison\n\n"
    report += f"![累计提交增长]({cumulative_relative})\n\n"
    report += "## Comparison of total number of submissions\n\n"
    report += f"![提交总数对比]({total_commits_relative})\n\n"





    # 保存报告
    report_path = "comparison_report.md"
    with open(report_path, "w", encoding="UTF-8") as f:
        f.write(report)
    print(f"📊 对比报告已生成: {report_path}")
    return report_path


def generate_cumulative_comparison_plot(all_repos_data):
    """生成累计提交增长对比图"""
    os.makedirs('visuals', exist_ok=True)
    plt.figure(figsize=(12, 7))

    # 使用专业配色方案
    colors = ['#1f77b4', '#ff7f0e']  # 为两个仓库定制颜色
    line_styles = ['-', '--']
    markers = ['o', 's']

    # 修复：使用seaborn设置网格样式
    sns.set_style("whitegrid")
    plt.grid(True, linestyle='--', alpha=0.7)

    # 确定共同起始日期
    all_start_dates = [min(data['dates']) for data in all_repos_data.values() if data['dates']]
    common_start = min(all_start_dates) if all_start_dates else None

    for i, (repo_name, data) in enumerate(all_repos_data.items()):
        if not data['dates']:
            continue

        dates = data['dates']
        cumulative = data['cumulative']

        # 对齐时间轴
        if common_start:
            filtered_dates = [date for date in dates if date >= common_start]
            filtered_cumulative = cumulative[-len(filtered_dates):] if filtered_dates else []
            plt.plot(filtered_dates, filtered_cumulative,
                     label=repo_name, linestyle=line_styles[i], linewidth=2.5,
                     color=colors[i], marker=markers[i], markevery=30, markersize=7)
        else:
            plt.plot(dates, cumulative, label=repo_name,
                     linestyle=line_styles[i], linewidth=2.5, color=colors[i])

    plt.title('累计提交增长对比', fontsize=16, fontweight='bold')
    plt.xlabel('日期', fontsize=12)
    plt.ylabel('累计提交数', fontsize=12)

    # 优化日期显示
    plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
    plt.gca().xaxis.set_major_locator(mdates.MonthLocator(interval=2))
    plt.gcf().autofmt_xdate()

    plt.legend(fontsize=12, loc='upper left')
    plt.tight_layout()

    # 使用固定文件名
    filename = "visuals/cumulative_comparison.png"
    plt.savefig(filename, format='png', dpi=300, bbox_inches='tight')
    plt.close()

    # 返回绝对路径确保正确引用
    return os.path.abspath(filename)


def generate_total_commits_plot(all_repos_data):
    """生成提交总数对比图"""
    os.makedirs('visuals', exist_ok=True)
    plt.figure(figsize=(10, 6))

    # 修复：使用seaborn设置网格样式
    sns.set_style("whitegrid")
    plt.grid(True, linestyle='--', alpha=0.7)

    # 准备数据
    repo_names = []
    total_commits = []
    for repo_name, data in all_repos_data.items():
        if data['total_commits'] > 0:
            repo_names.append(repo_name)
            total_commits.append(data['total_commits'])

    # 创建DataFrame并排序
    df = pd.DataFrame({
        '仓库': repo_names,
        '总提交数': total_commits
    }).sort_values('总提交数', ascending=False)

    # 定制颜色方案
    colors = ['#1f77b4', '#ff7f0e']

    # 创建条形图
    ax = sns.barplot(
        x='仓库',
        y='总提交数',
        data=df,
        hue='仓库',
        palette=colors,
        legend=False
    )

    # 添加数据标签
    max_value = max(total_commits) if total_commits else 1
    for i, v in enumerate(df['总提交数']):
        ax.text(i, v + max_value * 0.02, f"{v}",
                ha='center', fontsize=11, fontweight='bold')

    plt.title('提交总数对比', fontsize=16, fontweight='bold')
    plt.xlabel('仓库', fontsize=12)
    plt.ylabel('总提交数', fontsize=12)
    plt.xticks(rotation=0)  # 水平显示仓库名称
    plt.ylim(0, max_value * 1.15)
    plt.tight_layout()

    # 使用固定文件名
    filename = "visuals/total_commits.png"
    plt.savefig(filename, format='png', dpi=300, bbox_inches='tight')
    plt.close()

    # 返回绝对路径确保正确引用
    return os.path.abspath(filename)


def collect_repo_data(repo_name, repo_url):
    """收集仓库数据"""
    print(f"\n🔍 正在收集仓库数据: {repo_name}")
    repo_path = Path(repo_name)

    # 处理现有仓库
    if repo_path.exists() and (repo_path / ".git").exists():
        print(f"  使用现有仓库: {repo_path.resolve()}")
        repo = Repo(repo_path)

        # 添加实际的仓库更新逻辑
        print(f"  正在更新仓库...")
        try:
            origin = repo.remotes.origin
            origin.fetch()
            # 尝试合并更新
            current_branch = repo.active_branch
            origin.pull(current_branch.name)
            print("  ✓ 仓库更新成功")
        except Exception as e:
            print(f"  ! 更新仓库时出错: {str(e)}")
            return {'dates': [], 'cumulative': [], 'total_commits': 0}

    else:
        # 克隆新仓库
        print(f"  正在克隆仓库: {repo_url}")
        try:
            repo = Repo.clone_from(repo_url, repo_name)
            print("  ✓ 仓库克隆成功")
        except GitCommandError as e:
            print(f"  ! 克隆仓库时出错: {str(e)}")
            return {'dates': [], 'cumulative': [], 'total_commits': 0}

    # 收集提交数据
    print("  正在收集提交数据...")
    try:
        repo_commits = list(repo.iter_commits())
        commit_dates = sorted([datetime.fromtimestamp(c.authored_date) for c in repo_commits])
    except Exception as e:
        print(f"  ! 获取提交数据时出错: {str(e)}")
        return {'dates': [], 'cumulative': [], 'total_commits': 0}

    total = len(repo_commits)
    print(f"  找到 {total} 个提交")

    if commit_dates:
        print(f"  首次提交: {commit_dates[0].strftime('%Y-%m-%d')}")
        print(f"  最新提交: {commit_dates[-1].strftime('%Y-%m-%d')}")

    return {
        'dates': commit_dates,
        'cumulative': list(range(1, total + 1)),
        'total_commits': total
    }


def analyze_multiple_repos(repos_dict):
    """分析多个仓库并生成对比报告"""
    print("\n" + "=" * 50)
    print("开始分析仓库...")
    print("=" * 50)

    all_repos_data = {}
    for repo_name, repo_url in repos_dict.items():
        all_repos_data[repo_name] = collect_repo_data(repo_name, repo_url)

    print("\n" + "=" * 50)
    print("数据收集完成，生成报告中...")
    print("=" * 50)

    report_path = create_comparison_report(all_repos_data)

    print("\n" + "=" * 50)
    print(f"报告生成成功: {os.path.abspath(report_path)}")
    print("=" * 50)
    return report_path


if __name__ == "__main__":
    # 指定要对比的两个仓库
    repos_to_compare = {
        "AIFlowY": "https://gitee.com/aiflowy/aiflowy",
        "RuoYi-Vue": "https://gitee.com/y_project/RuoYi-Vue"
    }

    analyze_multiple_repos(repos_to_compare)